//-----------------解析和转化自定义脚本为HTML-----------------
function covToHTML(){
    var txt = $("#editor").val();
    //-----------------BOOK的标题页生成-----------------
    var book ={}//book对象
        book.vars = {}//存储宏变量
        book.tmps = {}//存储模板变量的函数
    //--/title{text}--标题
    setValOrder(txt,"title",function(val,match){
        book.title  = val;
        window.document.title = val;
        txt = txt.replace(match,"");
    });
    //--/subtitle{text}--副标题
    setValOrder(txt,"subtitle",function(val,match){
        book.subtitle  = "——" +  val;
        txt = txt.replace(match,"");
    });
    //--/subtitle{text}--副标题
    setValOrder(txt,"author",function(val,match){
        book.author  =  val;
        txt = txt.replace(match,"");
    });
    //--/subtitle{text}--副标题
    setValOrder(txt,"date",function(val,match){
        book.date  =  val;
        txt = txt.replace(match,"");
    });
    
    //--/BNP--BookNamePage--书名页
    try{
        var divs = BNPdiv("title",book) + BNPdiv("subtitle",book) + BNPdiv("author",book) + BNPdiv("date",book)
        var pageBK="<div class='pageBreak'></div>"//分页
        var BNP = "<div class='BNP'>" + divs + "</div>" + pageBK;

        txt = txt.replace(/\/BNP/,BNP)
    }catch(err) {
        console.log(err)
    }
    

    //-----------------实现Markdown的一些基础语法解析-----------------
    //H1~H6
    for(j=6;j>0;j--){
        var reg =eval("/#{" + j+ "}\\s{1}(.+)/g");
        txt = txt.replace(reg,"<h"+ j +">$1</h" + j +">");
    }
    // /dxSet指令--单选题集--/dxSet{题集标题}
    areaOrders(txt,"dxSet",function(i,m,head,foot,prms,recsStr){//遍历每个指令
       
        try{
                var str ="<div class='dxSet'>\n"
                    var setTitle = i+1 + "." + prms;//题集标题
                    str += "<div class='setTitle'>" + setTitle + "</div>\n";
                   
                splitEach(recsStr,"\n",function(i,set){
                    var rec_index = i+1 +".";
                    if(set.trim() != ""){
                        var itm = "<div class='Q'>" + rec_index +"$1</div>\n"//问题
                        itm += "<div class='opts'>\n||$2||</div>\n"//选项
                        itm += "<div class='ax'>【答案及分析】\n$3</div>"//答案
                    
                        itm = set.replace(/(.+)[|]{2}(.+)[|]{2}(.+)/g,itm)
    
                        var $2 = itm.match(/[|]{2}.+[|]{2}/g)[0].replace(/[|]{2}/g,"")
                        var opts ="";
                        splitEach($2,"|",function(i,opt){
                            opts += "<span>" + numToABC(i) + "." + opt + "</span>\n";
                        })
                        itm = itm.replace(/[|]{2}.+[|]{2}/g,opts)
                        str += itm
                    }
                    
                })
                str += "</div>";
                txt = txt.replace(head,"");
                txt = txt.replace(foot,"");
                txt = txt.replace(recsStr,str); 
        }catch(err) {
            console.log(err);
        }
    });

    
    //--图片--/pic{path|dsc}
    var itm = "<div class ='imgDiv'><img src='$1'></img><span class='imgDsc'>$2</span></div>";
    txt = txt.replace(/\/pic[{]{1}(.+)[|]{1}(.+)[}]{1}/g,itm)
    
    
    //--/pics指令--图片集--/pics{每行图片数}--只提供2、3、4
    areaOrders(txt,"pics",function(i,m,head,foot,prms,recsStr){//处理每个/pics指令
            var str = "<div class='picsDiv'>";

            //处理多行记录
            splitEach(recsStr,"\n",function(i,rec){
                if(rec.trim() != ""){
                    var itm  = "<div class ='imgDiv pics" + prms + "'>"
                    itm += "<img src='$1'></img>"
                    itm += "<span class='imgDsc'>$2</span>";
                    itm += "</div>";
                    str += rec.replace(/(.+)[|]{1}(.+)/g,itm);
                }
            })
            str += "</div>"
            txt = txt.replace(head,"");
            txt = txt.replace(foot,"");
            txt = txt.replace(recsStr,str); 
    });
    //--/table指令--图片集--/pics{每行图片数}--只提供2、3、4
    areaOrders(txt,"table",function(i,m,head,foot,prms,recsStr){//处理每个/table指令
        var prm = prms.split("|")
        var title = prm[0] 
        var class_name = prm[1] 
        var str = "<div class='table_div'>";
            str += "<div class='table_title'>" + title + "</div>";
            str += '<table class="' + class_name + '" cellpaiing="0" cellspacing=0>';
        
        //处理多行记录
        splitEach(recsStr,"\n",function(i,rec){
            if(rec.trim() != ""){
                var itm="";
                if(i==0){
                    itm  = '<tr class="tr1">'
                    splitEach(rec,"|",function(i,col){
                        itm += "<th>" + col
                    })
                }else{
                    itm = '<tr>'
                    splitEach(rec,"|",function(i,col){
                        itm += "<td>" + col
                    })
                }          
                str += itm;
            }
        })
        str += "</table>";
        str += "</div>";
        txt = txt.replace(head,"");
        txt = txt.replace(foot,"");
        txt = txt.replace(recsStr,str); 
    });
    //分栏
    areaOrders(txt,"cols",function(i,m,head,foot,prms,recsStr){
        var str = "<div style='column-count: "+ prms +";'>"
            str += recsStr
            str += "</div>"
        txt = txt.replace(head,"");
        txt = txt.replace(foot,"");
        txt = txt.replace(recsStr,str); 
    })
    //无序列表--ul
    areaOrders(txt,"ul",function(i,m,head,foot,prms,recsStr){
        var str = "<ul>"
            splitEach(recsStr,"\n",function(i,rec){
                if(rec.trim() != ""){
                var itm = "<li>" + rec;
                str += itm;
                }
            });
            str += "</ul>";
        txt = txt.replace(head,"");
        txt = txt.replace(foot,"");
        txt = txt.replace(recsStr,str); 
    })
    //有序列表--ol
    areaOrders(txt,"ol",function(i,m,head,foot,prms,recsStr){
        var str = "<ol>"
            splitEach(recsStr,"\n",function(i,rec){
                if(rec.trim() != ""){
                var itm = "<li>" + rec;
                str += itm;
                }
            });
            str += "</ol>";
        txt = txt.replace(head,"");
        txt = txt.replace(foot,"");
        txt = txt.replace(recsStr,str); 
    })
    //代码块--code
    areaOrders(txt,"code",function(i,m,head,foot,prms,recsStr){
        var str = "<div class='code'>"
            str += "<span>" + prms + "</span>"
            str += "<table cellpadding=0 cellspacing=0>"
            splitEach(recsStr,"\n",function(i,rec){
                var line_index = i+1;
                if(rec.trim() != ""){
                    rec = htmlEncode(rec);
                    rec = rec.replace(/\&lt;(.+)\&gt;/g,"&lt;<span style='color:#ffb6b6;'>$1</span>&gt;")
                    rec = rec.replace(/(\/{2}.+)/g,"<span style='color:#63ff63;'>$1</span>")
                    rec = rec.replace(/(function|var|for|if|else)/g,"<span style='color:#63beff;'>$1</span>")
                    rec = rec.replace(/([(]{1})(.+)([)]{1})/g,"<span style='color:#97d6d6;padding:0px 4px;'>$1</span><span style='color:#ff6363;'>$2</span><span style='color:#97d6d6;padding:0px 4px;'>$3</span>")
                    var itm = "<tr><td>" + line_index + "<td>" + rec;
                    str += itm;
                }
            });
            str += "</table>";
            str += "</div>";
        txt = txt.replace(head,"");
        txt = txt.replace(foot,"");
        txt = txt.replace(recsStr,str); 
    })
    //步骤--steps
    areaOrders(txt,"steps",function(i,m,head,foot,prms,recsStr){
        var str = "<div class='steps'>"
            str += "<div class='steps_title'>" + prms + "</div>"
            areaOrders(recsStr,"1",function(j,m,head,foot,pm,body){
                var step_index = j+1;
                var step = "<div class='step'>";
                    step += "<div class='step_title'><span>" + step_index + "</span>" + pm + "</div>"
                    step += "<div class='step_body'>" + body + "</div>";
                    step += "</div>"
                str += step;
            })
            str += "</div>";
        
        txt = txt.replace(m,str); 
    })
    //月历--month
    areaOrders(txt,"month",function(i,m,head,foot,prms,recsStr){
        var pm =prms.split("|");
        var month ={
            id:"month" + i,
            date:pm[0],
            title:pm[1]
        }
        var dt = month.date.split("-");
        month.year =dt[0];
        month.mon =dt[1];
        //1.生成并显示月历空表格
        var str = "<div class='month' id='" + month.id + "' data-year='" + month.year + "' data-month='" + month.mon + "'>\n<div class='month_title'>"+month.title+"</div>\n"
            str += "<table border=1 cellpadding=0 cellspacing=0>\n"
            str += "<tr><th>日<th>一<th>二<th>三<th>四<th>五<th>六\n"
            str += "<tr><td><td><td><td><td><td><td>".repeat(6)
            str += "</table>\n"
            str += "<textarea>" + recsStr.replace(/\n/g,"||") + "</textarea>\n"
            str += "</div>\n"
        txt = txt.replace(m,str); 

        
    })
    //变量宏--/$
    areaOrders(txt,"$",function(i,m,head,foot,prms,recsStr){
        //添加变量到book.vars
        eval("book.vars." + prms + "=recsStr")
        txt = txt.replace(m,"")
    })

    //在正文引用宏变量--$(var_name)
    $Orders(txt,function(i,m1,prms){
        var p = eval("book.vars." + prms)
            p = p.replace(/\n/g,"<p>")
        txt = txt.replace(m1,p);
    });

    //带参宏/$${var_name(prms_name)} ... //$$
    areaOrders(txt,"${2}",function(i,m,head,foot,prms,recsStr){//处理每个/pics指令
            var pp = prms.split("(");
            var tmp_name = pp[0];//函数名称
            var tmp_pms = pp[1].replace(")","")//函数形式参数
            //创建对象
            var obj = {}
                obj.tmp = recsStr;//模板正文
                obj.prms = tmp_pms.split(",")//形式参数集合
                obj.cov =function(args){//传入实际参数集合
                    var ags =args.split(",")
                    var tmp =this.tmp;
                    for(i=0;i<ags.length;i++){//遍历参数
                        //替换实际参数中传入的变量宏
                        if(ags[i].indexOf("$[")>-1){
                            ags[i] = ags[i].replace(/\${1}[\[]{1}(.+)[\]]{1}/g,"book.vars.$1")
                            ags[i] = eval(ags[i])
                        }
                        
                        tmp = tmp.replace(eval('/[{]{1}' + this.prms[i] + '[}]{1}/g'),ags[i]);
                    }
                    //处理模板中的for指令
                    var m_for = tmp.match(/\/{1}for[{]{1}.+[}]{1}[\s\S]*?\/{2}for/mg)
                    arrEach(m_for,function(i,mm){

                    })
                    return tmp;
                }

            eval("book.tmps." + tmp_name + "=obj")//给book.tmps对象添加对象
            txt = txt.replace(m,"");
            
    });
    //在正文引用模板宏--$$(var_name(args))
    $$Orders(txt,function(i,m1,prms){
        var pp = prms.split("(");
        var tmp_name = pp[0];
        var args = pp[1].replace(")","")
        //获取
        var tmp = eval("book.tmps." + tmp_name + ".cov('" + args + "')")
        
        txt = txt.replace(m1,tmp);
    });

    //--段落
    var match= txt.match(/.{2,}\s{1}/g);
    // console.log("p",match)
    try{
        for(i=0;i<match.length;i++){
            if(match[i].trim() != "" && match[i].match(/\<{1}.*\>{1}/g) == null){
                var itm = "<p>" + match[i] + "</p>";
                txt = txt.replace(match[i],itm)
            }
        }
    }catch(err) {}
    //换页指令
    txt = txt.replace(/\/newpage/g,"<div class='pageBreak'></div>")

    //bbcode
    txt = txt.replace(/\[{1}color=(.+?)\]{1}(.+?)\[\/color\]/g,"<span style='color:$1;'>$2</span>")
    txt = txt.replace(/\[{1}bg=(.+?)\]{1}(.+?)\[\/bg\]/g,"<span style='background-color:$1;'>$2</span>")

    txt = txt.replace(/\[{1}u\]{1}(.+?)\[\/u\]/g,"<u>$1</u>")
    //==================================页面填充HTML==================================
    var doc = window.frames["if1"].document
    try {
        doc.body.innerHTML =""
        doc.write($("#if_code").text())//写入HTML模板代码
        doc.title = book.title;
        $(doc).find(".main").html(txt);//写入内容代码
    } catch (err) {
        console.log(err)
    }
    
    
    
    //月历指令数据生成
    $(doc).find(".month").each(function(i,e){
        var me = $(this);
        var m_month ={
            year:parseInt(me.data("year")),
            mon:parseInt(me.data("month")),
            recsStr:me.find("textarea").text()
        }
        // me.children(".month_title").text(m_month.year+"年" + m_month.mon + "月")

        var m_date = new Date(m_month.year, m_month.mon-1,1);

        var start = m_date.getDay();//起始
        var days = new Date(m_month.year,m_month.mon,0).getDate();
        for(var i=1;i<=days;i++){
            me.find("td").eq(start + i-1).html("<span>" + i +"</span>");
        }

        //将记录数据添加到月历中
        splitEach(m_month.recsStr,"||",function(i,rec){
            if(rec.trim() != ""){
                var rc = rec.split("//");
                var day = parseInt(rc[0]);
                var html = "";
                splitEach(rc[1],"|",function(i,line){
                    html+= "<p>" + line + "</p>"
                });
                me.find("td").eq(start + day-1).append(html)
            }
            
        })
    })
    
//-----------------为章、节、列表、图片添加自动计数-----------------
    //为各级标题添加序号
    $(doc).find(".main>h1").each(function(i,e){
        var index = i+1;
        $(this).prepend("第" + index + "章 ").before(pageBK);//--<h1>--第i章 XXXX
        $(this).nextUntil("h1").filter("h2").each(function(j,em){
            var jIndex = j+1;
            $(this).prepend("第" + jIndex + "节 ");//--<h2>--第i节 XXXX
            $(this).nextUntil("h2").filter("h3").each(function(k,em){
                var kndex = k+1;
                $(this).prepend(jIndex + "." + kndex + " "); //--<h3>--j.k XXXX
                $(this).nextUntil("h3").filter("h4").each(function(f,em){
                    var fndex = f+1;
                    $(this).prepend(jIndex + "." + kndex + "." + fndex + " ")//--<h4>--j.k.f XXXX
                });
            });
        });
    });
    //--<img>--图片i XXXX
    $(doc).find("span.imgDsc").each(function(i,e){
        var index = i+1;
        $(this).prepend("图片" + index + " ")
    })
    //--<table>--表格i XXXX
    $(doc).find(".table_div>.table_title").each(function(i,e){
        var index = i+1;
        $(this).prepend("表格" + index + " ")
    })
    //生成目录
    toTOC();
    
}